using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Threading;
using Ricciolo.StylesExplorer.MarkupReflection;

namespace Ricciolo.StylesExplorer.Model.BamlResource
{
    class BamlResourceAssembly : NotifyObject, IAssembly
    {
        private readonly IApplication _application;
        private IList<IXamlFile> _xamlFiles;
        private string _name;

        public BamlResourceAssembly(IApplication application, string location, ITypeResolver resolver)
        {
            this._application = application;
            this._name = Path.GetFileName(location);

            BamlFile bamlFile = new BamlFile(new Uri(location, UriKind.RelativeOrAbsolute), File.OpenRead(location));
            this.XamlFiles.Add(new CompiledXamlFile(this, bamlFile, resolver));
        }

        #region IAssembly Members

        /// <summary>
        /// Restituisce il nome dell'assembly
        /// </summary>
        public string Name
        {
            get { return _name; }
        }

        /// <summary>
        /// Restituisce la lista dei files xaml nell'assembly
        /// </summary>
        public IList<IXamlFile> XamlFiles
        {
            get
            {
                if (_xamlFiles == null)
                    _xamlFiles = new XamlFileCollection(this.Invoker);
                return _xamlFiles;
            }
        }

        /// <summary>
        /// Restituisce il riferimento all'applicazione
        /// </summary>
        public IApplication Application
        {
            get { return _application; }
        }

        #endregion

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                foreach (IXamlFile xf in this.XamlFiles)
                {
                    if (xf is IDisposable)
                        ((IDisposable)xf).Dispose();
                }
                this.XamlFiles.Clear();
            }
        }
    }
}
